<template>
  <div class="user-detail-container">
    <!-- 头部导航 -->
    <div class="header">
      <router-link to="/users" class="back-link">
        <i class="icon-arrow-left"></i> 返回用户列表
      </router-link>
      <h1 class="page-title">用户详情</h1>
      <div class="actions">
        <button class="btn edit-btn" @click="toggleEditMode">
          {{ editMode ? '取消编辑' : '编辑用户' }}
        </button>
        <button class="btn danger-btn" @click="deleteUser">
          <i class="icon-delete"></i> 删除
        </button>
      </div>
    </div>

    <!-- 用户基本信息卡片 -->
    <div class="user-card">
      <div class="avatar-section">
        <div class="avatar-wrapper">
          <img :src="user.avatar" alt="用户头像" class="avatar" />
          <div v-if="editMode" class="avatar-edit" @click="triggerFileInput">
            <i class="icon-camera"></i>
            <input 
              type="file" 
              ref="fileInput" 
              accept="image/*" 
              @change="handleAvatarChange"
              class="file-input"
            />
          </div>
        </div>
        <div class="user-meta">
          <h2 v-if="!editMode" class="username">{{ user.name }}</h2>
          <input v-else v-model="editableUser.name" class="edit-input" />
          
          <div class="user-id">用户ID: {{ user.id }}</div>
          
          <div class="user-status">
            <span :class="['status-badge', user.status.toLowerCase()]">
              {{ user.status }}
            </span>
            <span v-if="editMode" class="status-selector">
              <select v-model="editableUser.status">
                <option value="活跃">活跃</option>
                <option value="禁用">禁用</option>
                <option value="待激活">待激活</option>
              </select>
            </span>
          </div>
        </div>
      </div>

      <div class="info-grid">
        <div class="info-item">
          <label>注册时间</label>
          <div>{{ formatDate(user.joinDate) }}</div>
        </div>
        <div class="info-item">
          <label>最后登录</label>
          <div>{{ relativeTime(user.lastLogin) }}</div>
        </div>
        <div class="info-item">
          <label>登录次数</label>
          <div>{{ user.loginCount }} 次</div>
        </div>
        <div class="info-item">
          <label>用户角色</label>
          <div v-if="!editMode">
            <span :class="['role-badge', user.role.toLowerCase()]">
              {{ user.role }}
            </span>
          </div>
          <div v-else>
            <select v-model="editableUser.role">
              <option value="管理员">管理员</option>
              <option value="编辑">编辑</option>
              <option value="用户">用户</option>
              <option value="访客">访客</option>
            </select>
          </div>
        </div>
      </div>
    </div>

    <!-- 用户信息编辑表单 -->
    <div v-if="editMode" class="edit-form">
      <div class="form-section">
        <h3 class="section-title">基本信息</h3>
        <div class="form-grid">
          <div class="form-group">
            <label>姓名</label>
            <input type="text" v-model="editableUser.name" class="form-input" />
          </div>
          <div class="form-group">
            <label>邮箱</label>
            <input type="email" v-model="editableUser.email" class="form-input" />
          </div>
          <div class="form-group">
            <label>手机号</label>
            <input type="tel" v-model="editableUser.phone" class="form-input" />
          </div>
          <div class="form-group">
            <label>职位</label>
            <input type="text" v-model="editableUser.position" class="form-input" />
          </div>
          <div class="form-group">
            <label>部门</label>
            <input type="text" v-model="editableUser.department" class="form-input" />
          </div>
        </div>
      </div>

      <div class="form-section">
        <h3 class="section-title">其他信息</h3>
        <div class="form-grid">
          <div class="form-group">
            <label>地址</label>
            <input type="text" v-model="editableUser.address" class="form-input" />
          </div>
          <div class="form-group">
            <label>城市</label>
            <input type="text" v-model="editableUser.city" class="form-input" />
          </div>
          <div class="form-group">
            <label>国家</label>
            <input type="text" v-model="editableUser.country" class="form-input" />
          </div>
          <div class="form-group">
            <label>邮政编码</label>
            <input type="text" v-model="editableUser.zipCode" class="form-input" />
          </div>
        </div>
      </div>

      <div class="form-section">
        <h3 class="section-title">账户设置</h3>
        <div class="form-grid">
          <div class="form-group">
            <label>密码</label>
            <div class="password-field">
              <input 
                type="password" 
                v-model="editableUser.password" 
                placeholder="输入新密码"
                class="form-input" 
              />
              <button class="generate-btn" @click="generatePassword">生成</button>
            </div>
            <div class="password-hint" v-if="editableUser.password">
              密码强度: <span :class="passwordStrengthClass">{{ passwordStrength }}</span>
            </div>
          </div>
          <div class="form-group">
            <label>双因素认证</label>
            <div class="toggle-switch">
              <input 
                type="checkbox" 
                id="twoFactor" 
                v-model="editableUser.twoFactorEnabled"
                class="toggle-input"
              />
              <label for="twoFactor" class="toggle-label"></label>
              <span>{{ editableUser.twoFactorEnabled ? '已启用' : '已禁用' }}</span>
            </div>
          </div>
        </div>
      </div>

      <div class="form-actions">
        <button class="btn primary-btn" @click="saveChanges">保存更改</button>
        <button class="btn secondary-btn" @click="toggleEditMode">取消</button>
      </div>
    </div>

    <!-- 用户活动记录 -->
    <div class="activity-section">
      <div class="section-header">
        <h2 class="section-title">用户活动记录</h2>
        <div class="filter-controls">
          <select v-model="activityFilter" class="filter-select">
            <option value="all">全部活动</option>
            <option value="login">登录记录</option>
            <option value="action">操作记录</option>
            <option value="system">系统事件</option>
          </select>
          <div class="date-range">
            <input type="date" v-model="startDate" class="date-input" />
            <span>至</span>
            <input type="date" v-model="endDate" class="date-input" />
          </div>
        </div>
      </div>

      <div class="activity-list">
        <div v-for="activity in filteredActivities" :key="activity.id" class="activity-item">
          <div class="activity-icon" :class="activity.type">
            <i :class="activity.icon"></i>
          </div>
          <div class="activity-content">
            <div class="activity-title">{{ activity.title }}</div>
            <div class="activity-description">{{ activity.description }}</div>
          </div>
          <div class="activity-time">{{ relativeTime(activity.time) }}</div>
        </div>
        
        <div v-if="filteredActivities.length === 0" class="empty-state">
          <i class="icon-file"></i>
          <p>没有找到相关活动记录</p>
        </div>
      </div>
    </div>

    <!-- 用户统计数据 -->
    <div class="stats-section">
      <h2 class="section-title">用户行为统计</h2>
      <div class="stats-grid">
        <div class="stat-card">
          <div class="stat-value">{{ user.loginCount }}</div>
          <div class="stat-label">总登录次数</div>
          <div class="stat-trend">
            <i class="icon-up"></i> 12% 较上月
          </div>
        </div>
        <div class="stat-card">
          <div class="stat-value">{{ userAvgSession }} 分钟</div>
          <div class="stat-label">平均会话时长</div>
          <div class="stat-trend">
            <i class="icon-down"></i> 3% 较上周
          </div>
        </div>
        <div class="stat-card">
          <div class="stat-value">{{ user.completedTasks }}</div>
          <div class="stat-label">完成任务数</div>
          <div class="stat-trend">
            <i class="icon-up"></i> 28% 较上月
          </div>
        </div>
        <div class="stat-card">
          <div class="stat-value">{{ user.engagementRate }}%</div>
          <div class="stat-label">参与度</div>
          <div class="stat-trend">
            <i class="icon-up"></i> 7% 较上周
          </div>
        </div>
      </div>
      
      <div class="chart-container">
        <div class="chart-header">
          <h3>最近30天登录频率</h3>
          <div class="chart-legend">
            <div class="legend-item">
              <span class="color-dot login"></span> 登录次数
            </div>
          </div>
        </div>
        <div class="login-chart">
          <div v-for="(day, index) in loginChartData" :key="index" class="chart-bar">
            <div class="bar-value" :style="{ height: day.logins * 5 + 'px' }"></div>
            <div class="bar-label">{{ day.day }}</div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { formatDate, relativeTime } from '@/utils/dateUtil';
import { validatePassword } from '@/utils/validate';
//import userService from '@/services/userService';

const route = useRoute();
const router = useRouter();

// 用户数据
const user = ref({
  id: route.params.id,
  name: '张明',
  avatar: '/images/avatars/user1.jpg',
  email: 'zhangming@example.com',
  phone: '13800138000',
  role: '管理员',
  status: '活跃',
  joinDate: '2023-01-15T08:30:00Z',
  lastLogin: '2023-10-25T14:20:00Z',
  loginCount: 142,
  completedTasks: 28,
  engagementRate: 82,
  position: '高级产品经理',
  department: '产品研发部',
  address: '北京市海淀区科技园区88号',
  city: '北京',
  country: '中国',
  zipCode: '100080',
  twoFactorEnabled: true
});

// 编辑模式状态
const editMode = ref(false);
const editableUser = ref({});
const fileInput = ref(null);

// 活动记录
const activityFilter = ref('all');
const startDate = ref('');
const endDate = ref('');

// 活动记录数据
const activities = ref([
  { id: 1, type: 'login', icon: 'icon-login', title: '用户登录', description: '从北京市登录系统', time: '2023-10-25T14:20:00Z' },
  { id: 2, type: 'action', icon: 'icon-edit', title: '更新个人资料', description: '修改了职位信息', time: '2023-10-24T10:15:00Z' },
  { id: 3, type: 'system', icon: 'icon-settings', title: '安全设置更新', description: '启用了双因素认证', time: '2023-10-23T16:45:00Z' },
  { id: 4, type: 'action', icon: 'icon-task', title: '完成任务', description: '完成了"产品需求分析"任务', time: '2023-10-22T09:30:00Z' },
  { id: 5, type: 'login', icon: 'icon-login', title: '用户登录', description: '从上海市登录系统', time: '2023-10-20T18:10:00Z' },
  { id: 6, type: 'action', icon: 'icon-upload', title: '文件上传', description: '上传了"项目计划书.pdf"', time: '2023-10-19T11:20:00Z' }
]);

// 登录图表数据
const loginChartData = ref([
  { day: '10/1', logins: 3 },
  { day: '10/2', logins: 5 },
  { day: '10/3', logins: 2 },
  { day: '10/4', logins: 4 },
  { day: '10/5', logins: 6 },
  { day: '10/6', logins: 1 },
  { day: '10/7', logins: 3 },
  { day: '10/8', logins: 4 },
  { day: '10/9', logins: 5 },
  { day: '10/10', logins: 7 },
  { day: '10/11', logins: 6 },
  { day: '10/12', logins: 4 },
  { day: '10/13', logins: 5 },
  { day: '10/14', logins: 3 },
  { day: '10/15', logins: 4 },
  { day: '10/16', logins: 6 },
  { day: '10/17', logins: 8 },
  { day: '10/18', logins: 7 },
  { day: '10/19', logins: 5 },
  { day: '10/20', logins: 4 },
  { day: '10/21', logins: 3 },
  { day: '10/22', logins: 5 },
  { day: '10/23', logins: 6 },
  { day: '10/24', logins: 7 },
  { day: '10/25', logins: 5 }
]);

// 计算属性
const filteredActivities = computed(() => {
  let result = [...activities.value];
  
  if (activityFilter.value !== 'all') {
    result = result.filter(a => a.type === activityFilter.value);
  }
  
  // 日期过滤逻辑（实际项目中需要实现）
  return result;
});

const passwordStrength = computed(() => {
  if (!editableUser.value.password) return '';
  
  if (editableUser.value.password.length < 6) return '弱';
  if (editableUser.value.password.length < 10) return '中等';
  return '强';
});

const passwordStrengthClass = computed(() => {
  return {
    'weak': passwordStrength.value === '弱',
    'medium': passwordStrength.value === '中等',
    'strong': passwordStrength.value === '强'
  };
});

const userAvgSession = computed(() => {
  return Math.floor(Math.random() * 20) + 15;
});

// 方法
const toggleEditMode = () => {
  editMode.value = !editMode.value;
  if (editMode.value) {
    // 进入编辑模式时复制用户数据
    editableUser.value = {...user.value, password: ''};
  }
};

const triggerFileInput = () => {
  fileInput.value.click();
};

const handleAvatarChange = (e) => {
  const file = e.target.files[0];
  if (file) {
    const reader = new FileReader();
    reader.onload = (event) => {
      editableUser.value.avatar = event.target.result;
    };
    reader.readAsDataURL(file);
  }
};

const generatePassword = () => {
  const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*';
  let password = '';
  for (let i = 0; i < 12; i++) {
    password += chars.charAt(Math.floor(Math.random() * chars.length));
  }
  editableUser.value.password = password;
};

const saveChanges = () => {
  // 实际项目中应调用API保存更改
  if (editableUser.value.password && !validatePassword(editableUser.value.password)) {
    alert('密码强度不足，请使用至少8位包含字母和数字的密码');
    return;
  }
  
  // 更新用户数据（实际项目中应调用API）
  user.value = {...editableUser.value};
  
  // 清除密码字段
  delete user.value.password;
  
  // 退出编辑模式
  editMode.value = false;
  
  alert('用户信息已更新');
};

const deleteUser = () => {
  if (confirm('确定要删除此用户吗？此操作不可撤销。')) {
    // 实际项目中应调用API删除用户
    router.push('/users');
  }
};

onMounted(() => {
  // 模拟API加载延迟
  setTimeout(() => {
    // 实际项目中应调用API获取用户详情
    console.log(`加载用户ID: ${route.params.id} 的详情`);
  }, 300);
});
</script>

<style scoped>
.user-detail-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30px;
  flex-wrap: wrap;
  gap: 15px;
}

.back-link {
  display: flex;
  align-items: center;
  color: #42b983;
  text-decoration: none;
  font-weight: 500;
}

.back-link i {
  margin-right: 5px;
}

.page-title {
  font-size: 24px;
  color: #2c3e50;
  margin: 0;
}

.actions {
  display: flex;
  gap: 10px;
}

.btn {
  padding: 8px 16px;
  border-radius: 4px;
  border: none;
  cursor: pointer;
  display: flex;
  align-items: center;
  gap: 5px;
  font-weight: 500;
  transition: all 0.3s;
}

.edit-btn {
  background: #f0f0f0;
  color: #333;
}

.edit-btn:hover {
  background: #e0e0e0;
}

.danger-btn {
  background: #fdeded;
  color: #e74c3c;
}

.danger-btn:hover {
  background: #fadbd8;
}

.user-card {
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
  padding: 25px;
  margin-bottom: 30px;
}

.avatar-section {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

.avatar-wrapper {
  position: relative;
  margin-right: 20px;
}

.avatar {
  width: 120px;
  height: 120px;
  border-radius: 50%;
  object-fit: cover;
  border: 3px solid #f0f2f5;
}

.avatar-edit {
  position: absolute;
  bottom: 5px;
  right: 5px;
  background: #42b983;
  width: 36px;
  height: 36px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  cursor: pointer;
  transition: all 0.3s;
}

.avatar-edit:hover {
  background: #3498db;
  transform: scale(1.1);
}

.file-input {
  display: none;
}

.user-meta {
  flex: 1;
}

.username {
  font-size: 28px;
  margin: 0 0 5px;
  color: #2c3e50;
}

.edit-input {
  font-size: 28px;
  padding: 5px 10px;
  border: 1px solid #ddd;
  border-radius: 4px;
  width: 300px;
}

.user-id {
  color: #7f8c8d;
  margin-bottom: 15px;
}

.user-status {
  display: flex;
  align-items: center;
  gap: 10px;
}

.status-badge {
  padding: 4px 12px;
  border-radius: 12px;
  font-size: 14px;
  font-weight: 500;
}

.status-badge.活跃 {
  background: #e8f6f0;
  color: #27ae60;
}

.status-badge.禁用 {
  background: #fdeded;
  color: #e74c3c;
}

.status-badge.待激活 {
  background: #fef9e7;
  color: #f39c12;
}

.info-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
  gap: 20px;
  border-top: 1px solid #eee;
  padding-top: 20px;
}

.info-item {
  display: flex;
  flex-direction: column;
}

.info-item label {
  font-weight: 500;
  color: #7f8c8d;
  margin-bottom: 5px;
  font-size: 14px;
}

.role-badge {
  padding: 4px 12px;
  border-radius: 12px;
  font-size: 14px;
  font-weight: 500;
}

.role-badge.管理员 {
  background: #e8f4ff;
  color: #3498db;
}

.role-badge.编辑 {
  background: #fff8e6;
  color: #f39c12;
}

.role-badge.用户 {
  background: #f0f5ff;
  color: #9b59b6;
}

/* 编辑表单样式 */
.edit-form {
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
  padding: 25px;
  margin-bottom: 30px;
}

.form-section {
  margin-bottom: 30px;
}

.section-title {
  font-size: 18px;
  color: #2c3e50;
  margin-bottom: 15px;
  padding-bottom: 10px;
  border-bottom: 1px solid #eee;
}

.form-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 20px;
}

.form-group {
  display: flex;
  flex-direction: column;
}

.form-group label {
  font-weight: 500;
  margin-bottom: 8px;
  color: #555;
}

.form-input {
  padding: 10px 15px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 16px;
  transition: border-color 0.3s;
}

.form-input:focus {
  border-color: #42b983;
  outline: none;
  box-shadow: 0 0 0 2px rgba(66, 185, 131, 0.2);
}

.password-field {
  display: flex;
  gap: 10px;
}

.generate-btn {
  padding: 0 12px;
  background: #f0f0f0;
  border: 1px solid #ddd;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s;
}

.generate-btn:hover {
  background: #e0e0e0;
}

.password-hint {
  margin-top: 5px;
  font-size: 14px;
}

.password-hint .weak {
  color: #e74c3c;
}

.password-hint .medium {
  color: #f39c12;
}

.password-hint .strong {
  color: #27ae60;
}

.toggle-switch {
  display: flex;
  align-items: center;
  gap: 10px;
}

.toggle-input {
  display: none;
}

.toggle-label {
  position: relative;
  display: inline-block;
  width: 50px;
  height: 24px;
  background: #ddd;
  border-radius: 12px;
  cursor: pointer;
  transition: background 0.3s;
}

.toggle-label:after {
  content: '';
  position: absolute;
  width: 20px;
  height: 20px;
  border-radius: 50%;
  background: white;
  top: 2px;
  left: 2px;
  transition: transform 0.3s;
}

.toggle-input:checked + .toggle-label {
  background: #42b983;
}

.toggle-input:checked + .toggle-label:after {
  transform: translateX(26px);
}

.form-actions {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  padding-top: 15px;
  border-top: 1px solid #eee;
}

.primary-btn {
  background: #42b983;
  color: white;
}

.primary-btn:hover {
  background: #3498db;
}

.secondary-btn {
  background: #f0f0f0;
  color: #333;
}

.secondary-btn:hover {
  background: #e0e0e0;
}

/* 活动记录样式 */
.activity-section {
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
  padding: 25px;
  margin-bottom: 30px;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
  gap: 15px;
  margin-bottom: 20px;
}

.filter-controls {
  display: flex;
  align-items: center;
  gap: 15px;
}

.filter-select {
  padding: 8px 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  background: white;
}

.date-range {
  display: flex;
  align-items: center;
  gap: 10px;
}

.date-input {
  padding: 8px;
  border: 1px solid #ddd;
  border-radius: 4px;
}

.activity-list {
  max-height: 400px;
  overflow-y: auto;
}

.activity-item {
  display: flex;
  align-items: center;
  padding: 15px;
  border-bottom: 1px solid #f0f2f5;
  transition: background 0.3s;
}

.activity-item:hover {
  background: #f9f9f9;
}

.activity-icon {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 15px;
  font-size: 18px;
}

.activity-icon.login {
  background: #e8f6f0;
  color: #27ae60;
}

.activity-icon.action {
  background: #e8f4ff;
  color: #3498db;
}

.activity-icon.system {
  background: #fef9e7;
  color: #f39c12;
}

.activity-content {
  flex: 1;
}

.activity-title {
  font-weight: 500;
  margin-bottom: 5px;
}

.activity-description {
  color: #7f8c8d;
  font-size: 14px;
}

.activity-time {
  color: #7f8c8d;
  font-size: 14px;
}

.empty-state {
  text-align: center;
  padding: 40px;
  color: #7f8c8d;
}

.empty-state i {
  font-size: 48px;
  margin-bottom: 15px;
  opacity: 0.5;
}

/* 统计区域样式 */
.stats-section {
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
  padding: 25px;
}

.stats-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
  gap: 20px;
  margin-bottom: 30px;
}

.stat-card {
  background: #f8f9fa;
  border-radius: 8px;
  padding: 20px;
  text-align: center;
}

.stat-value {
  font-size: 32px;
  font-weight: bold;
  margin-bottom: 5px;
  color: #2c3e50;
}

.stat-label {
  color: #7f8c8d;
  margin-bottom: 10px;
}

.stat-trend {
  font-size: 14px;
  color: #27ae60;
}

.stat-trend .icon-down {
  color: #e74c3c;
}

.chart-container {
  background: #f8f9fa;
  border-radius: 8px;
  padding: 20px;
  margin-top: 20px;
}

.chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.chart-legend {
  display: flex;
  gap: 15px;
}

.legend-item {
  display: flex;
  align-items: center;
  gap: 5px;
  font-size: 14px;
}

.color-dot {
  width: 12px;
  height: 12px;
  border-radius: 50%;
}

.color-dot.login {
  background: #42b983;
}

.login-chart {
  display: flex;
  align-items: flex-end;
  height: 200px;
  gap: 10px;
  padding: 0 20px;
}

.chart-bar {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.bar-value {
  width: 30px;
  background: #42b983;
  border-radius: 4px 4px 0 0;
  transition: height 0.5s ease;
}

.bar-label {
  margin-top: 8px;
  font-size: 12px;
  color: #7f8c8d;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .header {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .actions {
    width: 100%;
    justify-content: flex-end;
  }
  
  .avatar-section {
    flex-direction: column;
    text-align: center;
  }
  
  .avatar-wrapper {
    margin-right: 0;
    margin-bottom: 15px;
  }
  
  .section-header {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .filter-controls {
    width: 100%;
    justify-content: space-between;
  }
}
</style>